package com.internetCafes.spms.web.toolbox.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.core.exception.RRException;
import com.internetCafes.spms.web.sys.entity.dto.qualiconf.QualiCertDeleteDto;
import com.internetCafes.spms.web.sys.entity.dto.qualiconf.QualiConfigCertConfigDto;
import com.internetCafes.spms.web.sys.entity.vo.qualiconf.QualiConfigCertConfigVo;
import com.internetCafes.spms.web.sys.model.ConfInfo;
import com.internetCafes.spms.web.sys.service.ConfInfoService;
import com.internetCafes.spms.web.toolbox.entity.QualiCertCond;
import com.internetCafes.spms.web.toolbox.entity.QualiCertCondGroup;
import com.internetCafes.spms.web.toolbox.entity.QualiConfRecord;
import com.internetCafes.spms.web.toolbox.entity.po.QualiCertCondPo;
import com.internetCafes.spms.web.toolbox.mapper.QualiCertCondMapper;
import com.internetCafes.spms.web.toolbox.service.IQualiCertCondGroupService;
import com.internetCafes.spms.web.toolbox.service.IQualiCertCondService;
import com.internetCafes.spms.web.toolbox.service.IQualiConfRecordService;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 资质证书条件信息表 服务实现类
 * </p>
 *
 * @author Zj
 * @since 2021-06-13
 */
@Service
public class QualiCertCondServiceImpl extends ServiceImpl<QualiCertCondMapper, QualiCertCond> implements IQualiCertCondService {


    @Autowired
    private IQualiCertCondGroupService iQualiCertCondGroupService;
    @Autowired
    private IQualiConfRecordService iQualiConfRecordService;
    @Autowired
    private ConfInfoService confInfoService;

    /**
     * 批量删除证书条件
     *
     * @param dto 请求参数
     */
    @Override
    public void qualiConfigCertDeleteBatch(QualiCertDeleteDto dto) {
        if (CollectionUtils.isNotEmpty(dto.getCertIds())) {
            deleteGroupByRecordIds(dto.getCertIds());
        }
    }

    /**
     * 证书条件删除
     *
     * @param id 条件记录id
     */
    @Override
    public void qualiConfigCertDelete(Long id) {

        deleteGroupByRecordIds(id);

        iQualiConfRecordService.removeById(id);
    }

    /**
     * 删除多参数
     *
     * @param recordIds
     */
    public void deleteGroupByRecordIds(Long... recordIds) {
        List<Long> ids = Arrays.asList(recordIds);
        deleteGroupByRecordIds(ids);
    }

    /**
     * 根据证书条件记录id 删除组
     *
     * @param recordIds 记录id
     */
    public void deleteGroupByRecordIds(List<Long> recordIds) {
        QueryWrapper<QualiCertCondGroup> queryWrapperOfGroup = new QueryWrapper<>();
        queryWrapperOfGroup.in("record_id", recordIds);
        List<QualiCertCondGroup> groupPos = iQualiCertCondGroupService.list(queryWrapperOfGroup);

        if (CollectionUtils.isNotEmpty(groupPos)) {
            List<Long> groupIds = groupPos.stream()
                    .map(QualiCertCondGroup::getId)
                    .collect(Collectors.toList());
            QueryWrapper<QualiCertCond> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("group_id", groupIds);
            baseMapper.delete(queryWrapper);

            iQualiCertCondGroupService.removeByIds(groupIds);
        }
    }

    /**
     * 证书条件修改编辑
     *
     * @param dto 请求参数
     */
    @Override
    public QualiConfigCertConfigVo qualiConfigCertEdit(QualiConfigCertConfigDto dto) {
        /*
         * 原有数据验证
         * 1-删除原有条件记录
         * 2-修改主要信息，证书信息重新入录
         */
        QualiConfRecord qualiConfRecordPo = iQualiConfRecordService.getById(dto.getId());
        if (ObjectUtils.isEmpty(qualiConfRecordPo)) {
            throw new RRException("数据不存在");
        }

        deleteGroupByRecordIds(dto.id);

        return qualiConfigCertConfig(dto);
    }

    /**
     * 证书条件添加
     *
     * @param dto 请求参数
     */
    @Override
    public QualiConfigCertConfigVo qualiConfigCertConfig(QualiConfigCertConfigDto dto) {
        /*
         * 1-创建记录
         * 2-创建分组
         * 3-保存条件信息
         */
        QualiConfRecord qualiConfRecordDo = new QualiConfRecord();
        BeanUtils.copyProperties(dto, qualiConfRecordDo);
        qualiConfRecordDo.setExplains(dto.getExplain());
        if (ObjectUtils.isNull(qualiConfRecordDo.getId()) || qualiConfRecordDo.getId().equals(0)) {
            iQualiConfRecordService.save(qualiConfRecordDo);
        } else {
            iQualiConfRecordService.updateById(qualiConfRecordDo);
        }

        QualiCertCondGroup qualiCertCondGroupDo = new QualiCertCondGroup();
        qualiCertCondGroupDo.setRecordId(qualiConfRecordDo.getId())
                .setCondTag(dto.getCondTag())
                .setGroupNum(1)
                .setGoupRank(1);
        iQualiCertCondGroupService.save(qualiCertCondGroupDo);

        List<QualiCertCond> qualiCertCondDos = dto.getCertInfos().stream()
                .map(certInfo -> {
                    QualiCertCond qualiCertCond = new QualiCertCond();
                    BeanUtils.copyProperties(certInfo, qualiCertCond);
                    qualiCertCond.setGroupId(qualiCertCondGroupDo.getId());
                    return qualiCertCond;
                })
                .collect(Collectors.toList());
        saveBatch(qualiCertCondDos);

        Map<String, List<ConfInfo>> certTypeGroup = confInfoService.certTypeGroup();

        QualiConfigCertConfigVo qualiConfigCertConfigVo = new QualiConfigCertConfigVo();
        BeanUtils.copyProperties(dto, qualiConfigCertConfigVo);
        qualiConfigCertConfigVo.setId(qualiConfRecordDo.getId());
        qualiConfigCertConfigVo.setContent(contentSplicing(qualiCertCondDos, dto.getCondTag().equals(1) ? "并":"或", certTypeGroup));
        return qualiConfigCertConfigVo;
    }

    /**
     * 证书条件拼接
     *
     * @param certConds 证书条件列表
     * @return 结果
     */
    @Override
    public String contentSplicing(List<QualiCertCond> certConds, String splicingWord, Map<String, List<ConfInfo>> certTypeGroup) {


        return certConds.stream()
                .map(certCond -> {
                    String prefix = "";
                    if (!StringUtil.isBlank(certCond.getProfessionCode())) {
                        prefix = certCond.getProfessionCode();
                    } else {
                        if (!StringUtil.isBlank(certCond.getCategoryCode())) {
                            prefix = certCond.getCategoryCode();
                        } else {
                            if (StringUtil.isBlank(certCond.getTypeCode())) {
                                return prefix;
                            }
                            prefix = StringUtil.isBlank(certTypeGroup.get(certCond.getTypeCode()).get(0).getName()) ? "" : certTypeGroup.get(certCond.getTypeCode()).get(0).getName();
                        }
                    }
                    if (certCond.getCompleteFlag().equals(1)) {
                        return prefix + "专业齐全";
                    }
                    return prefix + certCond.getAmount() + "本";
                })
                .collect(Collectors.joining(splicingWord));
    }

    /**
     * 获取证书条件列表 通过groupId
     *
     * @param groupId 组id
     * @return 证书列表
     */
    @Override
    public List<QualiCertCondPo> getCertListByGroupId(Long groupId) {
        return null;
    }

    /**
     * 获取证书条件列表 通过groupId
     *
     * @param recordId 记录id
     * @return 证书列表
     */
    @Override
    public List<QualiCertCondPo> getCertListByRecordId(Long recordId) {
        return baseMapper.selectQualiCerts(new QueryWrapper<QualiCertCond>().eq("xqccg.record_id", recordId));
    }

    /**
     * 获取证书条件列表 通过groupId
     *
     * @param qualiId 记录id
     * @return 证书列表
     */
    @Override
    public List<QualiCertCondPo> getCertListByQualiId(Long qualiId) {
        return baseMapper.selectQualiCerts(new QueryWrapper<QualiCertCond>().eq("xqcr.quali_conf_id", qualiId));
    }

    /**
     * 获取证书条件列表 通过groupId
     *
     * @param wrapper 查询条件
     * @return 证书列表
     */
    @Override
    public List<QualiCertCondPo> getCertList(Wrapper<QualiCertCond> wrapper) {
        return baseMapper.selectQualiCerts(wrapper);
    }


}
